﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Thinker.SignChannel.Dto;
using Thinker.SignChannel.Records;
using Thinker.SignChannel.Repositories;
using Volo.Abp.Application.Dtos;

namespace Thinker.SignChannel.Signs;

public class SignAppService(
    RecordManager recordManager,
    IPersonRepository personRepository,
    ITimeRepository timeRepository) :
    SignChannelAppService, ISignAppService
{
    public async Task<SignRecordDto> AddAsync(SignInput input)
    {
        var idNumber = input.IdNumber;
        var info = await recordManager.AddAsync(idNumber!, input.PersonName!);
        return info.ToSignRecordDto(ObjectMapper);
    }

    public async Task<PagedResultDto<string>> FindIdNumberAsync(FindIdNumberInput input)
    {
        var query = await personRepository.GetQueryableAsync();
        query = query.Where(x => x.IdNumber.Contains(input.IdNumber!));
        var total = await AsyncExecuter.CountAsync(query);

        query = query.PageBy(input);
        var list = await AsyncExecuter.ToListAsync(query.Select(x => x.IdNumber));
        return new PagedResultDto<string>(total, list);
    }

    public async Task<ProgressDto> GetProgressAsync()
    {
        var time = await timeRepository.FindByTimeAsync(DateTime.Now);
        if (time == null)
        {
            return new ProgressDto();
        }

        var timeId = time.Id;
        var total = await recordManager.CountTotalAsync(timeId);
        var done = await recordManager.CountSignedAsync(timeId);
        return new ProgressDto
        {
            Total = total,
            Done = done
        };
    }
}